<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;
use App\Traits\ApiResponsable;

class Handler extends ExceptionHandler
{
    use ApiResponsable;
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
    ];

    /**
     * Report or log an exception.
     *
     * This is a great spot to send exceptions to Sentry, Bugsnag, etc.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        if ($this->shouldntReport($exception)) {
            return;
        }
        parent::report($exception);
        // 渲染页面
        $response = parent::render(null, $exception);
        // 保存到文件
        $fileName = $this->saveReport($response);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        // 渲染页面
        $response = parent::render($request, $exception);
        // 判断是否处于调试状态
        if (env('APP_DEBUG', config('app.debug', false))) {
            // 调试状态下返回错误信息
            return $this->error($exception->getMessage(), 500, $exception->__toString());
        } else {
            // 非调试状态下只说明服务器发生错误
            return $this->error('服务器发生错误');
        }
    }

    /**
     * 保存错误报告
     *
     * 返回错误报告的文件名
     *
     * @param string $content
     * @return string
     */
    private function saveReport($content)
    {
        $randCode = strval(time()) . rand(10000, 99999);
        $fileName = $randCode . '.html';
        $reportPath = realpath(ROOT_PATH . '/storage/reports');
        $filePath = $reportPath . '/' . $fileName;
        $file = fopen($filePath, "w");
        fwrite($file, $content);
        return $fileName;
    }
}
